<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>条形码识别测试</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/quagga/0.12.1/quagga.min.js"></script>
</head>
<body>
    <!-- 摄像头展示区域 -->
	<div class="box">
		<div id="canvanCode" style="border: 1px solid red;"></div>
		<button class="box-button" onclick="openQuagga()">开始识别</button>
		<input class="box-input" id="resultCode"/>
	</div>
	
    
    <script>
		function openQuagga(){
			Quagga.init({
			    inputStream : {
			        name : "Live",
			        type : "LiveStream",
					constraints: {
						width: 500,
						height: 1000,
					},
			        target: document.querySelector('#canvanCode')
			    },
			    decoder : {
			        readers : ["ean_reader",'code_39_reader'],
			        debug: {
			            drawBoundingBox: false,
			            showFrequency: false,
			            drawScanline: false,
			            showPattern: false,
			        },
			        multiple: false
			    }
			}, ()=>{
			    //打开摄像头
			    Quagga.start();
				//data.codeResult.code就是摄像头扫描出的商品条形码
				//Tip:只要摄像头一识别到条形码就会显示在控制台，有时候一识别就显示十几行条形码，所以我们可以使用节流，减少扫码的次数。
			    Quagga.onDetected(function(data){
			        // alert(data.codeResult.code)
			        document.querySelector('#resultCode').value = data.codeResult.code
			        
					Quagga.stop();
			    });
			});
		}
		
    </script>
</body>
</html>
<style>
	.box{
		border: 1px solid #000;
		width: 100vw;
		height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	.box-button{
		padding: 10px;
		font-size: 20px;
		margin: 20px 0;
	}
	.box-input{
		width: 50%;
		font-size: 40px;
	}
</style>
